package com.aaa.dao.impl;

import com.aaa.dao.BaseDao;
import com.aaa.dao.CategoryDao;
import com.aaa.entity.Category;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

public class CategoryDaoImpl implements CategoryDao {
    private BaseDao baseDao = BaseDao.getInstance();

    @Override
    public int addCategory(Category category) {
        String sql = "insert into category (name,status,momo) values(?,?,?)";
        Object[] objects = {category.getName(),category.getStatus(),category.getMomo()};
        return baseDao.executeUpdate(sql,objects);
    }

    @Override
    public int updateCategory(Category category) {
        String sql = "update category set name=?,status=?,momo=? where id=?";
        Object[] objects = {category.getName(),category.getStatus(),category.getMomo(),category.getId()};
        return  baseDao.executeUpdate(sql,objects);
    }

    @Override
    public int changeStatus(Category category) {
        String sql = "update category set status=? where id=?";
        Object[] objects = {category.getStatus(),category.getId()};
        return  baseDao.executeUpdate(sql,objects);
    }

    @Override
    public List<Category> getCategoryList() {
        String sql = "select id,name from category where status!=0";
        List<Category> categoryList = baseDao.query(sql,null,Category.class);
        return categoryList;
    }

    @Override
    public List<Category> getAllCategoryList(Integer pageNumber, Integer pageSize, String searchId, String searchName) {
        String sql = "select * from category where 1=1";
        if(StringUtils.isNotBlank(searchId)){
            sql += " and id = "+searchId;
        }
        if(StringUtils.isNotBlank(searchName)){
            searchName = "%" + searchName + "%";
            sql += " and name like '" + searchName + "'";
        }
        sql += " limit ?,?";
        Object[] params = {pageNumber,pageSize};
        List<Category> list = baseDao.query(sql,params,Category.class);
        return list;
    }

    @Override
    public int getAllCategoryInfoCount(String searchId, String searchName) {
        String sql = "select count(1) len from category where 1=1";
        if (StringUtils.isNotBlank(searchId)) {
            sql += " and id = " + searchId;
        }
        if(StringUtils.isNotBlank(searchName)){
            searchName = "%"+searchName+"%";
            sql += "and name like '"+searchName+"'";
        }
        List<Map<String, Object>> maps = baseDao.query(sql, null);
        if (maps != null && maps.size() > 0) {
            Map<String, Object> map = maps.get(0);
            Integer res = Integer.parseInt(map.get("len") + "");
            return res;
        }
        return 0;
    }
}
